package com.gmq.interceptor;

import com.alibaba.fastjson.JSON;
import com.gmq.common.BaseContext;
import com.gmq.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//检查用户是否登录
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private BaseContext baseContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s = request.getRequestURL().toString();
        if (s.contains("login") || s.contains("logout") || s.contains("backend") || s.contains("front")) {
            return true;
        }
        Object employee = request.getSession().getAttribute("employee");
        Object userId = request.getSession().getAttribute("userId");
        if (employee != null) {
            baseContext.setThreadLocal((Long) request.getSession().getAttribute("employee"));
            return true;
        }
        if (userId != null) {
            baseContext.setThreadLocal((Long) request.getSession().getAttribute("userId"));
            return true;
        }
        log.info("未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
